package seclog.client;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;

import seclog.wireformats.MessageType;

public class ClientListener extends Thread
{
	private int listenport;
	
	public ClientListener(String listenport)
	{
		this.listenport = Integer.parseInt(listenport);
	}
	
	public int getListenPort()
	{
		return listenport;
	}

	public void run()
	{
		ServerSocket sock = null;
		try {
			sock = new ServerSocket(listenport);
		} catch (IOException e) {
			System.out.println("Unable to listen the socket port: " + e.getMessage());
			e.printStackTrace();
		}

	    // for each incoming connection spawn a thread
	    while (!Thread.interrupted()) 
	    {
	    	try {
				new Thread(new Handler(sock.accept())).start();
			} catch (IOException e) {
				System.out.println("Unable to spawn thread: " + e.getMessage());
				e.printStackTrace();
			}
	    }     
   	}
	
	private class Handler implements Runnable
    {
		final Socket socket;

        private Handler(Socket socket)
        {
        	this.socket = socket;
        }
        
        public void run()
        {
        	try {
        	
        		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
        		String line = br.readLine();        
        		
        		while (line != null && line.length() != 0) {
        			System.out.println("Line is: " + line);
        			
        			// read more
        			line = br.readLine();
        		}
        	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
        	// close socket
        	try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}        	

			
/*        	ObjectInputStream  ois = null;
    		try {
				ois = new ObjectInputStream(getSocket().getInputStream());
			} catch (IOException e) {
				System.out.println("Unable to get an object input stream: " + e.getMessage());
				e.printStackTrace();
			}

    		MessageType mt = null;
            try {
				mt = (MessageType)ois.readObject();
			} catch (IOException e) {
				System.out.println("Unable to get MessageType object: " + e.getMessage());
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				System.out.println("Unable to locate MessageType class: " + e.getMessage());
				e.printStackTrace();
			}            	

       		
			System.out.println("Type is: " + mt.getMessageType());
*/
        }
        
        private Socket getSocket()
        {        	
        	return socket;
        }
    }
}
